package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.ProductStock;
import cn.wolfcode.wms.domain.SaleAccount;
import cn.wolfcode.wms.domain.StockOutcomeBill;
import cn.wolfcode.wms.domain.StockOutcomeBillItem;
import cn.wolfcode.wms.mapper.ProductStockMapper;
import cn.wolfcode.wms.mapper.SaleAccountMapper;
import cn.wolfcode.wms.mapper.StockOutcomeBillItemMapper;
import cn.wolfcode.wms.mapper.StockOutcomeBillMapper;
import cn.wolfcode.wms.query.PageResult;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IStockOutcomeBillService;
import cn.wolfcode.wms.util.LogicRuntimeException;
import cn.wolfcode.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class StockOutcomeBillServiceImpl implements IStockOutcomeBillService{

	@Autowired
	private StockOutcomeBillMapper mapper;
	@Autowired
	private StockOutcomeBillItemMapper itemMapper;
	@Autowired
	private ProductStockMapper productStockMapper;
	@Autowired
	private SaleAccountMapper saleAccountMapper;
	
	@Override
	public void insert(StockOutcomeBill stockOutcomeBill) {
		//录入时间
		stockOutcomeBill.setInputTime(new Date());
		//录入人
		stockOutcomeBill.setInputUser(UserContext.getUser());
		
		List<StockOutcomeBillItem> items = stockOutcomeBill.getItems();
		//总数量
		BigDecimal totalNumber = BigDecimal.ZERO;
		//总金额
		BigDecimal totalAmount = BigDecimal.ZERO;
		for (StockOutcomeBillItem item : items) {
			//小计
			item.setAmount(item.getSalePrice().multiply(item.getNumber()));
			totalNumber=totalNumber.add(item.getNumber());
			totalAmount=totalAmount.add(item.getAmount());
		}
		stockOutcomeBill.setTotalNumber(totalNumber);
		stockOutcomeBill.setTotalAmount(totalAmount);
		mapper.insert(stockOutcomeBill);
		
		//订单id
		for (StockOutcomeBillItem item : items) {
			item.setBillId(stockOutcomeBill.getId());
			//保存明细
			itemMapper.insert(item);
		}
	}

	@Override
	public void deleteByPrimaryKey(Long id) {
		mapper.deleteByPrimaryKey(id);
		itemMapper.deleteByBillId(id);
	}

	@Override
	public void updateByPrimaryKey(StockOutcomeBill stockOutcomeBill) {
		//删除旧的明细
		itemMapper.deleteByBillId(stockOutcomeBill.getId());
		//修改订单,总数,总额,
		List<StockOutcomeBillItem> items = stockOutcomeBill.getItems();
		//总数量
		BigDecimal totalNumber = BigDecimal.ZERO;
		//总金额
		BigDecimal totalAmount = BigDecimal.ZERO;
		for (StockOutcomeBillItem item : items) {
			//小计
			item.setAmount(item.getSalePrice().multiply(item.getNumber()));
			totalNumber=totalNumber.add(item.getNumber());
			totalAmount=totalAmount.add(item.getAmount());
			//保存明细
			item.setBillId(stockOutcomeBill.getId());
			itemMapper.insert(item);
		}
		stockOutcomeBill.setTotalNumber(totalNumber);
		stockOutcomeBill.setTotalAmount(totalAmount);
		
		mapper.updateByPrimaryKey(stockOutcomeBill);
	}

	@Override
	public StockOutcomeBill selectByPrimaryKey(Long id) {
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	public List<StockOutcomeBill> selectAll() {
		return mapper.selectAll();
	}

	@Override
	public PageResult query(QueryObject qo) {
		int totalCount = mapper.queryForCount(qo);
		if (totalCount == 0) {
			return new PageResult(qo.getPageSize());
		}
		List<StockOutcomeBill> listData = mapper.queryForList(qo);
		return new PageResult(qo.getCurrentPage(), qo.getPageSize(), listData, totalCount);
	}

	@Override
	public void audit(Long id) {
		//根据id查询订单
		StockOutcomeBill stockOutcomeBill = mapper.selectByPrimaryKey(id);
		//判断该订单是否已审核
		if (stockOutcomeBill.getStatus()==StockOutcomeBill.STATUS_NORMAL) {
			//设置状态
			stockOutcomeBill.setStatus(StockOutcomeBill.STATUS_AUDITED);
			//设置审核人
			stockOutcomeBill.setAuditor(UserContext.getUser());
			//设置审核时间
			stockOutcomeBill.setAuditTime(new Date());
			//审核订单 更新数据
			mapper.audit(stockOutcomeBill);
			//更新库存
			//根据商品id和仓库id 查询商品库存数据
			//遍历
			Long depotId = stockOutcomeBill.getDepot().getId();
			for (StockOutcomeBillItem item : stockOutcomeBill.getItems()) {
				ProductStock stock = productStockMapper.selectByProductIdAndDepotId(item.getProduct().getId(),depotId);
				//判断库存中是否有该商品
				if (stock==null) {//不存在
					throw new LogicRuntimeException("["+item.getProduct().getName()+" 商品]在["+ stockOutcomeBill.getDepot().getName() +" 仓库]中不存在");
				}
				if (stock.getStoreNumber().compareTo(item.getNumber()) < 0) {//判断数量是否足够
					throw new LogicRuntimeException("["+item.getProduct().getName()+"]在["+stockOutcomeBill.getDepot().getName()+"]中数量["+stock.getStoreNumber()+"]不足["+item.getNumber()+"]");
				}else {
					//修改总额
					BigDecimal Amount = stock.getAmount().subtract(item.getNumber().multiply(stock.getPrice()));
					stock.setAmount(Amount);
					//修改总数
					BigDecimal storeNumber = stock.getStoreNumber().subtract(item.getNumber());
					stock.setStoreNumber(storeNumber);
					//更新数据
					productStockMapper.updateByPrimaryKey(stock);
				}
			}
			for (StockOutcomeBillItem item : stockOutcomeBill.getItems()) {
				ProductStock stock = productStockMapper.selectByProductIdAndDepotId(item.getProduct().getId(),depotId);
				//创建销售帐对象
				SaleAccount sale = new SaleAccount();
				//设置业务时间
				sale.setVdate(stockOutcomeBill.getVdate());
				//设置销售数量
				sale.setNumber(item.getNumber());
				//设置成本价
				sale.setCostPrice(stock.getPrice());
				//设置成本总额
				sale.setCostAmount(sale.getCostPrice().multiply(sale.getNumber()));
				//设置销售价
				sale.setSalePrice(item.getSalePrice());
				//设置销售总额
				sale.setSaleAmount(item.getSalePrice().multiply(sale.getNumber()));
				//设置商品id
				sale.setProductId(item.getProduct().getId());
				//设置客户id
				sale.setClientId(stockOutcomeBill.getClient().getId());
				//设置销售人id
				sale.setSalemanId(stockOutcomeBill.getInputUser().getId());
				//保存销售帐
				saleAccountMapper.insert(sale);

			}
		}
	}
}
